package com.ttx.pattern.example.iterator.after;

/**
 * 具体容器类
 * @author TimFruit
 * @date 19-6-12 下午10:47
 */
public class ConcreteAggregate implements Iterable<String> {

    private int size;
    private String[] elementData;


    public ConcreteAggregate() {
        elementData=new String[2];
    }

    @Override
    public Iterator<String> iterator() {
        return new InnerIterator();
    }


    // ------------------------------- 具体容器完成 添加元素, 删除元素 的操作
    public void add(String e){
        ensureCapacity(size+1);
        this.elementData[size]=e;
        size++;
    }

    public void remove(String e){
        int index=indexOf(e);
        if(index<0){
            return;
        }
        remove(index);
    }

    public String remove(int index){
        if(index<0 || index>=size){
            throw new IllegalArgumentException("超出边界");
        }

        String e=elementData[index];

        System.arraycopy(elementData, index+1, elementData, index, size-index-1);
        elementData[size-1]=null;
        size--;

        return e;
    }


    private void ensureCapacity(int minCapacity){

        if(minCapacity <= elementData.length){
            return;
        }

        if(elementData.length==Integer.MAX_VALUE){
            throw new RuntimeException("容器容量已达到最大值, 不能再扩容");
        }

        int newCapacity=elementData.length + (elementData.length>>1);

        if(newCapacity<0){ // 溢出, 使用最大值
            newCapacity=Integer.MAX_VALUE;
        }

        String[] ele=new String[newCapacity];

        System.arraycopy(elementData, 0, ele, 0, size);

        elementData=ele;

    }


    private int indexOf(String e){
        int i=0;
        for(;i<size;i++){
            if(e.equals(elementData[i])){
                return i;
            }
        }
        return -1;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder("[");
        for(int i=0; i< size; i++){
            sb.append(elementData[i]);
            sb.append(", ");
        }
        sb.replace(sb.lastIndexOf(","), sb.length(), "]");
        return sb.toString();
    }


    // -------------------------------




    // 具体迭代器
    private class InnerIterator implements Iterator<String>{

        private int cursor =0;  // 指针指向下一个元素
        private int lastRet = -1; // 指针指向上一次返回的元素, -1 表示没有


        @Override
        public boolean hasNext() {
            return cursor <size;
        }

        @Override
        public String next() {
            String e= elementData[cursor];
            lastRet=cursor;
            cursor++;
            return e;
        }

        @Override
        public String remove() {
            if(lastRet== -1){
                throw new IllegalStateException(); //不能移除两次
            }
            String e=ConcreteAggregate.this.remove(lastRet);
            cursor=lastRet;
            lastRet=-1;
            return e;
        }
    }
}
